
/**
 * 
 * @type @exp;View@call;extend
 */
var ImagesView = View.extend(ImagesView = {
    
    upload_callback: null,
    upload_url: $("#image_upload_url").val(),
    
    init: function() {
        this.configureImageUploader();
    },
    
    load_manager: function(callback) {
        var url = $("#image_manager_url").val();

        $.get(url, function(data) {
            if( callback && $.isFunction(callback) ) {
                callback(data);
            }
        });
    },
    
    show_manager: function() {
        
        this.load_manager(function(data) {
            $("#ajaxModal").html(data);
            $("#ajaxModal").modal();

            $(".tag_list").autocomplete({
                source: '/memberz/admin/images/tag_list', //$(this).data('url'),
                minLength: 2,
                select: function(event, ui) {
                    $(this).val( ui.item.value.name );
                    $(this).data("tag-id", ui.item.value.id );
                    $(this).attr("disabled", true).addClass('tagged');
                    $(this).parent().find(".tag_remove").show();
                    
                    $("#images_editor #save-changes-btn").removeAttr("disabled");
                    
                    event.preventDefault();
                },
                focus: function(event, ui) {
                    $(this).val( ui.item.value.name );
                    event.preventDefault();
                },
                change: function(event, ui) {
                    if( ui.item ) {
                       $(this).val( ui.item.value.name );
                       event.preventDefault();
                    }
                }
            });
            
            $(".tag_remove").click(function() {
                $(this).hide();
                $(this).parent().find(".tag_list").removeAttr("disabled").removeData("tag-id").removeClass("tagged").val("");
                
                if( $(".image-item .input.tagged").length == 0 ) {
                     $("#images_editor #save-changes-btn").attr("disabled", true);
                }
            });
        });
    },
    /**
     * Configures the ImageBox for handling and displaying images for the Game
     **/
    configureImageUploader: function() {
        var self = this;

        $("#img-frame").load(function() {
            var frame = this;
            var frame_content = null;

            if( window.navigator.userAgent.indexOf("MSIE") != -1 ) {
                if( frame.contentWindow.document.body.innerHTML != "" ) {
                    frame_content = frame.contentWindow.document.body.innerHTML;
                }
            } else {
                if( frame.contentDocument.body.innerHTML != "" ) {
                    frame_content = frame.contentDocument.body.innerHTML;
                }
            }

            if( frame_content != null ) {
                var info = $.parseJSON(frame_content);
                
                if( info && self.upload_callback && $.isFunction(self.upload_callback) ) {
                    self.upload_callback(info);
                }
            }
        });

        // provide a handler for the first upload handler
        $(".img-uploader").click(function(e) {


        }).change(function() {
            self.handleImageUpload(this);
        });
        
        $("#images_editor #save-changes-btn").click(function() {
            self.processTaggedImages();
        });
    },
    
    setUploadCallback: function(callback) {
        this.upload_callback = callback;
    },
    
    /**
     * Handles the upload for the specified file field
     * 
     * @param field the input[type=file] field to process
     **/
    handleImageUpload: function(url, fields, callback) {
        $("#game_image_box").css("background-image", "none");
        $("#instruction").show().html("Uploading Image. Please Wait...");

        var upload_form = document.createElement("form");
        upload_form.target = "img-frame";
        upload_form.action = url;
        upload_form.enctype = "multipart/form-data";
        upload_form.method = "post";

        //upload_form.appendChild(field);
        
        for(var i = 0; i < fields.length; i++) {
            $(upload_form).append(fields[i]);
        }
        

        upload_form.submit();
        
        this.setUploadCallback(callback);
    },
    
    /**
     * 
     */
    processTaggedImages: function() {
        
        if( $(".image-item .input.tagged").length == 0 ) {
            alert("No Images Have Been Tagged With Members. Please Tag An Image And Try Again");
            return;
        }
        
        var tag_url = $("#image_tag_url").val();
        var params = {
            tags: {}
        };
        
        $(".image-item .input.tagged").each(function() {
            var member_id = $(this).data("tag-id");
            var image_id = $(this).parents(".image-item").data("image-id");
            params['tags'][image_id] = member_id;
        });
        
        $.ajax({
            type: 'post',
            url: tag_url,
            data: params,
            dataType: 'json',
            success: function(res) {
                console.log(res);
                alert(res);
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    },
    
    /**
     * sample params
     * {
     *    selector: '#upload-btn',
     *    target_view: '#profile-image',
     *    url: $("#upload-url").val(),
     *    params: {
     *        member_id: $("#member_id").val()
     *    }
     * }
     */
    quickUploader: function(params) {
        var self = this;
        
        var fields = [];
        
        for(var key in params.params) {
            var input = $("<input />").attr({type: 'hidden', name: key}).val( params.params[key] );
            fields.push(input);
        }
         
        // create
        var new_upfile = $("<input />").attr({
            type: 'file',
            name: 'uploadfile',
            id: 'uploadfile'
        }).css({
            display: 'none',
            position: 'absolute'
        }).change(function() {
            fields.push(this);

            self.handleImageUpload(self.upload_url, fields, function(json) {
                var image = json.image.MemberImage;
                $(params.target_view).css("background-image", "url(" + image.file_url + ")"); // appRoot from jquery.multiple_uploads.js
                
                if( params['callback'] && $.isFunction(params['callback']) ) {
                    params.callback(image);
                }
            });
        });
            
        $(params.target_view).append(new_upfile);
        
        $(params.selector).click(function() {
            new_upfile.trigger('click');
        });
    }
});